/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package deque;

import accessori.DLNode;
import exceptions.EmptyDequeException;

/**
 *
 * @author pc
 */
class MyDeque<E> implements Deque<E> {

    private DLNode header, trailer;
    private int size;

    public MyDeque() {
        size = 0;
        header = new DLNode();
        trailer = new DLNode();

        header.setNext(trailer);
        trailer.setPrev(header);

        header.setPrev(null);
        trailer.setNext(null);

    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0 ? true : false;
    }

    @Override
    public E getFirst() throws EmptyDequeException {
        return (E) header.getNext().getElement();
    }

    @Override
    public E getLast() throws EmptyDequeException {
        return (E) trailer.getPrev().getElement();
    }

    @Override
    public void addFirst(E element) {

        if (header.getNext().equals(trailer)) {
            header.setNext(new DLNode(element, header, trailer));
            trailer.setPrev(header.getNext());
        } else {
            DLNode tmp = header.getNext();
            header.setNext(new DLNode(element, header, tmp));
            tmp.setPrev(header.getNext());

        }

    }

    @Override
    public void addLast(E element) {

        if (trailer.getPrev().equals(header)) {
            trailer.setPrev(new DLNode(element, header, trailer));
            header.setNext(trailer.getPrev());
        } else {
            DLNode tmp = trailer.getPrev();
            trailer.setPrev(new DLNode(element, tmp, trailer));
            tmp.setNext(trailer.getPrev());

        }


    }

    @Override
    public E removeFirst() throws EmptyDequeException {
        DLNode tmp = header.getNext();
        header.setNext(tmp.getNext());
        tmp.getNext().setPrev(header);



        return (E) tmp.getElement();
    }

    @Override
    public E removeLast() throws EmptyDequeException {
        DLNode tmp = trailer.getPrev();
        trailer.setPrev(tmp.getPrev());
        tmp.getPrev().setNext(trailer);
        
        return (E) tmp.getElement();
    }
}
